#!/usr/bin/env python3
"""
libtar MCP Server

面向 libtar 软件的命令行操作封装，提供以下 MCP tools：

1. libtar_compile_test - 编译 libtar 测试程序
   参数：source_file (源文件路径), output_name (输出文件名), include_dir (头文件目录)
   返回：包含编译结果的 JSON

2. libtar_create_archive - 创建 tar 归档文件
   参数：test_program (测试程序路径)
   返回：包含打包结果的 JSON

3. libtar_extract_archive - 解压 tar 归档文件
   参数：test_program (测试程序路径)
   返回：包含解压结果的 JSON

所有工具返回统一 JSON 结构：
{
  "success": bool,
  "command": str,
  "exit_code": int,
  "stdout": str,
  "stderr": str
}
"""

import subprocess
import shlex
from typing import List
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("libtar MCP Server")

@mcp.tool()
def libtar_compile_test(source_file: str, output_name: str = "tartest", include_dir: str = "$HOME/local/include") -> dict:
    """
    编译 libtar 测试程序
    
    参数:
        source_file: 源文件路径（如 tartest.c）
        output_name: 输出可执行文件名，默认为 tartest
        include_dir: 头文件目录，默认为 $HOME/local/include
    
    返回:
        JSON 结构包含编译结果
    """
    command = f"gcc -o {shlex.quote(output_name)} {shlex.quote(source_file)} -I{shlex.quote(include_dir)} -ltar"
    
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def libtar_create_archive(test_program: str = "./tartest") -> dict:
    """
    使用 libtar 创建 tar 归档文件
    
    参数:
        test_program: 测试程序路径，默认为 ./tartest
    
    返回:
        JSON 结构包含打包结果
    """
    command = f"{shlex.quote(test_program)} tar"
    
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def libtar_extract_archive(test_program: str = "./tartest") -> dict:
    """
    使用 libtar 解压 tar 归档文件
    
    参数:
        test_program: 测试程序路径，默认为 ./tartest
    
    返回:
        JSON 结构包含解压结果
    """
    command = f"{shlex.quote(test_program)} untar"
    
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": command,
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

if __name__ == "__main__":
    mcp.run()